/* 
 * %W% %E% Enrique Madrid
 *
 * Copyright (c) 1975-2008 M&T Consulting, Inc. All rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
*/

package com.myt.tools.obtk;

// Import Openbravo packages
import com.myt.tools.obtk.openbravo.account.*;

// Import M&T packages
import com.myt.util.att.*;

// Import Java packages
import java.util.*;

public class Main extends AttApp {

    HashMap<String, AttApp> command = new HashMap<String,AttApp>();

    private static String CMD_NAME_CSV2XML = "csv2xml";
    private static String CMD_NAME_XML2CSV = "xml2csv";

    public Main() {
	// Setting general options supported

	// Setting commands supported
	command.put(CMD_NAME_CSV2XML, new CmdCsv2Xml(CMD_NAME_CSV2XML));
	command.put(CMD_NAME_XML2CSV, new CmdXml2Csv(CMD_NAME_XML2CSV));
    }


    public static void main(String[] args) {

	Main app = new Main();

	app.exec(args);
    }

    public void exec(String[] args) {

	// Command position
	int i = lookUpCommand(args);

	if (i < 0) {
	    printHelp();
	}
	else {
	    AttApp cmd = (AttApp)command.get(args[i]);

	    String[] appOptions = buildArgs(args, 0, i);
	    
	    String[] cmdOptions = buildArgs(args, i + 1, args.length);

	    if (!parseOptions(appOptions) || hasOption("h")) {
		// Options error o user need help
		printHelp();
	    } else {
		// Execute command
		cmd.exec(cmdOptions);
	    }
	}
   }

    private int lookUpCommand(String [] args) {
	int ret = -1;
	Iterator it = command.keySet().iterator();
	while (it.hasNext() && (ret < 0)) {
	    String key = (String)it.next();
	    for (int i = 0; i < args.length; i++) {
		if (key.compareTo(args[i]) == 0) {
		    ret = i;
		    break;
		}
	    }
	}
	return ret;
    }

    public void printHelp() {

	System.out.println("Usage :");
	System.out.print("\tobtk [options] <command> [arguments]\n\n");

	super.printHelp();

	System.out.print("\nCommands:\n");
	System.out.print("--------\n\n");
	Iterator it = command.keySet().iterator();
	while (it.hasNext()) {
	    String key = (String)it.next();
	    AttApp cmd = (AttApp)command.get(key);
	    cmd.printHelp(key);
	    System.out.print("\n");
	}

    }
    
}